package com.lt.flashcard.model.entity;

import java.util.ArrayList;
import java.util.List;

import com.lt.flashcard.model.service.EcommerceService;
import com.lt.flashcard.model.service.FlashcardSetService;
import com.lt.flashcard.model.service.Repository;

/**
 * Represent the card of a user
 * @author ocsen
 *
 */
public class Cart {

	private int pricetotal = 0;
	
	private int cointotal = 0;
	
	private List<CartItem> items = new ArrayList<CartItem>();
	
	public int getPricetotal() {
		return pricetotal;
	}

	public void setPricetotal(int pricetotal) {
		this.pricetotal = pricetotal;
	}

	public int getCointotal() {
		return cointotal;
	}

	public void setCointotal(int cointotal) {
		this.cointotal = cointotal;
	}

	public List<CartItem> getItems() {
		return items;
	}

	public void setItems(List<CartItem> items) {
		this.items = items;
	}
	
	public int getTotalItems() {
		return getItems().size();
	}
	
	/**
	 * Check whether this flashcard already contains product with id
	 * @param id
	 * @return
	 */
	public boolean contains(Long id) {
		for(CartItem item : getItems()) {
			if(item.getProductid().equals(id))
				return true;
		}
		return false;
	}
	
	/**
	 * Remove a product from cart
	 * @param id
	 */
	public void remove(Long id) {
		for(int i = 0; i < items.size(); i++) {
			CartItem item = getItems().get(i);
			if(item.getProductid().equals(id)) {
				items.remove(i);
				pricetotal -= item.getProductprice();
				cointotal -= item.getProductcoin();
				break;
			}
		}
	}
	
	public void addItem(CartItem item) {
		if(!contains(item.getProductid())) {
			items.add(item);
			pricetotal += item.getProductprice();
			cointotal += item.getProductcoin();
		}
	}
	
	/**
	 * Add a flashcardset to cart
	 * @param id
	 */
	public void addItem(Long id) {
		if(contains(id))
			return;
		
		FlashcardSetService srv = Repository.getInstance().getFlashcardSetService();
		EcommerceService ecm = Repository.getInstance().getEcommerceService();
		FlashcardSet fcs = srv.findByID(id);
		if(fcs != null) {
			CartItem item = new CartItem(fcs.getId(), fcs.getName(), fcs.getPriceEflashcard(), ecm.priceToCoin(fcs.getPriceEflashcard()));
			item.setProductimage(fcs.getImage());
			item.setProductdescription(fcs.getDescription());
			addItem(item);
		}
	}
	
	@Override
	public String toString() {
		StringBuilder s = new StringBuilder();
		s.append(String.format("Cart<price: %s, coin: %s>[", pricetotal, cointotal));
		for(CartItem item : items)
			s.append(item.toString());
		s.append("]");
		return s.toString();
	}
}
